package com.sprouting.ops.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sprouting.ops.interfaces.ConstantBase;
import com.sprouting.ops.model.DromaraFileStorage;
import com.sprouting.ops.model.OpsUser;
import com.sprouting.ops.utils.UserTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

/**
 * 自动填充数据
 * 注意事项：
 *      自动填充是直接给实体类的属性设置值
 *      如果属性没有值，入库时会是 null
 *      MetaObjectHandler 提供的默认方法策略是：如果属性有值则不覆盖，如果填充值为 null 则不填充
 *      字段必须声明 @TableField 注解，并设置 fill 属性来选择填充策略
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2024/9/7 21:12
 */
@Slf4j
@Component
public class AutofillConfig implements MetaObjectHandler {

    /**
     * 新增的时候插入的数据
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("自动填充插入数据");
        OpsUser loginUser = UserTool.getLoginUser();
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateId", String.class, loginUser.getId());
        this.strictInsertFill(metaObject, "createId", String.class, loginUser.getId());
        this.strictInsertFill(metaObject, "delType", Integer.class, ConstantBase.DelType.ADD);
    }

    /**
     * 更新时插入的数据
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("自动填充更新数据");
        Object originalObject = metaObject.getOriginalObject();
        if (originalObject instanceof DromaraFileStorage){
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (servletRequestAttributes == null){
                // web环境才自动更新，才有登录人员信息
                return;
            }
        }

        OpsUser loginUser = UserTool.getLoginUser();
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateId", String.class, loginUser.getId());
    }
}
